package selection;

import java.util.ArrayList;
import java.util.Random;

import model.Chromosome;

public class SigamaScaling implements Selection {
	Random rand= new Random();
	@Override
	public Chromosome[] selectPatents(ArrayList<Chromosome> population) {
		// making average
		double average = 0;

		for (Chromosome chromosome : population) {
			average += chromosome.getFitness();
		}
		average /= population.size();
		double distance = 0;
		for (Chromosome chromosome : population) {
			distance += Math.pow((average - chromosome.getFitness()), 2);
		}
		distance /= population.size();
		double sigma = Math.sqrt(distance);

		for (Chromosome chromosome : population) {
			if (sigma != 0)
				chromosome.setExpVal(1 + (chromosome.getFitness() - average)
						/ (2 * sigma));
			else
				chromosome.setExpVal(1);
		}
		double sum=0;
		for (Chromosome chromosome : population) {
			sum+=chromosome.getExpVal();
		}
		//select parents
		double sum2=0;
		double flag=rand.nextDouble();
		Chromosome parent1=null;
		for (Chromosome chromosome : population) {
			sum2+=chromosome.getExpVal()/sum;
			if(flag<sum2)
			{
				parent1 = chromosome;
				break;
			}
		}
		flag=rand.nextDouble();
		sum2=0;
		Chromosome parent2=null;
		for (Chromosome chromosome : population) {
			sum2+=chromosome.getExpVal()/sum;
			if(flag<sum2)
			{
				parent2 = chromosome;
				break;
			}
		}
		
		return new Chromosome[] {parent1,parent2};
	}
	@Override
	public String toString() {
		return "SigamaScaling";
	}
}
